<template>
  <div class="bullet-trend-chart">
    <div class="chart-container" ref="chartContainer">
      <!-- 图表将在这里渲染 -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import type { BulletPredictItem, PriceHistory } from '@/types/bulletPrice'

// Props
const props = defineProps<{
  items: BulletPredictItem[]
  selectedItem?: BulletPredictItem | null
}>()

// 响应式数据
const chartContainer = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return

  chartInstance = echarts.init(chartContainer.value)
  
  // 设置图表配置
  const option = getChartOption()
  chartInstance.setOption(option)

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 获取图表配置
const getChartOption = () => {
  const selectedItem = props.selectedItem || props.items[0]
  
  if (!selectedItem || !selectedItem.price_history.length) {
    return getEmptyChartOption()
  }

  // 处理价格历史数据
  const priceHistory = selectedItem.price_history
    .slice()
    .sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime())

  const dates = priceHistory.map(item => {
    const date = new Date(item.timestamp)
    return `${date.getMonth() + 1}/${date.getDate()}`
  })
  
  const prices = priceHistory.map(item => item.price)
  const currentPrice = selectedItem.current_price
  const predictPrice = selectedItem.predict_price

  // 添加预测点
  const today = new Date()
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  dates.push(`${tomorrow.getMonth() + 1}/${tomorrow.getDate()}`)
  prices.push(predictPrice)

  return {
    title: {
      text: selectedItem.name,
      textStyle: {
        fontSize: 14,
        fontWeight: 'normal'
      },
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const dataIndex = params[0].dataIndex
        const isPredict = dataIndex === prices.length - 1
        const price = params[0].value
        const date = params[0].axisValue
        
        return `
          <div style="padding: 8px;">
            <div style="margin-bottom: 4px; font-weight: bold;">
              ${date} ${isPredict ? '(预测)' : ''}
            </div>
            <div style="color: ${isPredict ? '#409eff' : '#303133'};">
              价格: ${price.toLocaleString()} 哈夫币
            </div>
          </div>
        `
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e4e7ed',
      borderWidth: 1,
      textStyle: {
        color: '#303133',
        fontSize: 12
      }
    },
    grid: {
      left: '10%',
      right: '10%',
      top: '25%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#909399',
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#909399',
        fontSize: 10,
        formatter: (value: number) => {
          if (value >= 1000) {
            return `${(value / 1000).toFixed(1)}k`
          }
          return value.toString()
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f5f7fa',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '价格',
        type: 'line',
        data: prices,
        smooth: true,
        lineStyle: {
          width: 2,
          color: '#409eff'
        },
        itemStyle: {
          color: '#409eff',
          borderWidth: 2,
          borderColor: '#fff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(64, 158, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(64, 158, 255, 0.05)'
              }
            ]
          }
        },
        markPoint: {
          data: [
            {
              name: '预测价格',
              coord: [dates.length - 1, predictPrice],
              itemStyle: {
                color: '#f0a020'
              },
              label: {
                show: true,
                position: 'top',
                formatter: '预测',
                fontSize: 10,
                color: '#f0a020'
              }
            }
          ]
        }
      }
    ]
  }
}

// 获取空图表配置
const getEmptyChartOption = () => {
  return {
    title: {
      text: '暂无数据',
      textStyle: {
        fontSize: 14,
        color: '#909399'
      },
      left: 'center',
      top: 'middle'
    },
    xAxis: {
      show: false
    },
    yAxis: {
      show: false
    },
    series: []
  }
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return
  
  const option = getChartOption()
  chartInstance.setOption(option, true)
}

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 监听props变化
watch(() => props.selectedItem, () => {
  nextTick(() => {
    updateChart()
  })
}, { deep: true })

watch(() => props.items, () => {
  nextTick(() => {
    updateChart()
  })
}, { deep: true })

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 组件卸载
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.bullet-trend-chart {
  width: 100%;
  height: 100%;
  min-height: 200px;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>
